package com.tool.emulator.apple2.ui;

import javax.swing.*;
import javax.swing.plaf.basic.BasicBorders;
import java.awt.*;
import java.util.ArrayList;

/**
 * StatusBar.java @author tl 2011-6-27
 */
public class StatusBar extends JComponent {
	public final JLabel label = new JLabel("Ready");
	public final ArrayList<Component> list = new ArrayList<Component>();

	public StatusBar() {
		this.add(label);
		label.setFont(new Font("Dialog", 0, 16));
		label.setBorder(BasicBorders.getTextFieldBorder());
		this.setLayout(new LayoutManager() {

			public void addLayoutComponent(String name, Component comp) {
			}

			public void removeLayoutComponent(Component comp) {
			}

			public Dimension preferredLayoutSize(Container parent) {
				return label.getPreferredSize();
			}

			public Dimension minimumLayoutSize(Container parent) {
				return label.getMinimumSize();
			}

			public void layoutContainer(Container parent) {
				resizeComponents();
			}

		});
	}

	public void setStatus(String s) {
		if (s == null || s.length() == 0)
			s = "Ready";
		this.label.setText(s);
	}

	private void resizeComponents() {
		int w = this.getWidth();
		for (int i = this.list.size() - 1; i >= 0; i--) {
			Component c = this.list.get(i);
			Dimension sz = c.getPreferredSize();
			sz.width = Math.max(sz.width, 80);
			c.setBounds(w - sz.width, (this.getHeight() - sz.height) / 2, sz.width, sz.height);
			w -= c.getWidth();
		}
		Dimension sz = label.getPreferredSize();
		if (w > 0)
			label.setBounds(0, (this.getHeight() - sz.height) / 2, w, sz.height);
		else
			label.setBounds(w - sz.width, (this.getHeight() - sz.height) / 2, sz.width, sz.height);
	}

	public void addStatusComponent(Component c) {
		this.list.add(c);
		this.add(c);
	}

	public JLabel addStatusComponent(String text) {
		JLabel lbl = new JLabel(text);
		lbl.setBorder(BasicBorders.getTextFieldBorder());
		this.addStatusComponent(lbl);
		lbl.setHorizontalAlignment(JLabel.CENTER);
		lbl.setOpaque(true);
		return lbl;
	}

	public StatusConf newStatusConf(String text, Color back, Color fore) {
		return new StatusConf(text, back, fore);
	}

	public void setStatus(JLabel lbl, StatusConf conf) {
		if (conf.text != null) lbl.setText(conf.text);
		lbl.setForeground(conf.fore);
		lbl.setBackground(conf.back);
	}

	public class StatusConf {
		public final String text;
		public final Color back;
		public final Color fore;

		StatusConf(String text, Color back, Color fore) {
			super();
			this.text = text;
			this.back = back == null ? label.getBackground() : back;
			this.fore = fore == null ? label.getForeground() : fore;
		}
	}
}
